﻿using System;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace YJKAreaCutter.Utils.XDataUtils
{
	public class SmokeXDataManager
	{
		public static bool WriteSmokeXData(Element ele, ElementId RoomId)
		{
			bool result = false;
			try
			{
				SmokeXDataManager.Instance();
				Entity entity = SmokeXDataManager.m_xdataMgr.CreateEntity();
                SmokeXDataManager.m_xdataMgr.SetElementEntity<int>(ele, SmokeXDataManager.m_strFieldName, RoomId.IntegerValue, (DisplayUnitType)(-2), ref entity);
				SmokeXDataManager.m_xdataMgr.SetElementXData(ele, entity);
				result = true;
			}
			catch
			{
			}
			return result;
		}

		public static ElementId ReadSmokeXData(Element ele)
		{
			ElementId result = ElementId.InvalidElementId;
			try
			{
                result = new ElementId(XDataManager.GetElementXData<int>(SmokeXDataManager.m_Guid, ele, SmokeXDataManager.m_strFieldName, (DisplayUnitType)(-2)));
			}
			catch
			{
			}
			return result;
		}

		private static XDataManager Instance()
		{
			if (SmokeXDataManager.m_xdataMgr == null)
			{
				SchemaManager schemaManager = new SchemaManager(new SchemaData(SmokeXDataManager.m_Guid, SmokeXDataManager.m_schemaName, ""));
                schemaManager.AddField<int>(SmokeXDataManager.m_strFieldName, (UnitType)(-2));
				SmokeXDataManager.m_xdataMgr = new XDataManager(schemaManager);
				SmokeXDataManager.m_xdataMgr.FinishSchema();
			}
			return SmokeXDataManager.m_xdataMgr;
		}

		private static Guid m_Guid = new Guid("FCBE3CEE-3AC7-45DA-9098-0288DEC0D6EE");

		private static string m_schemaName = "SmokeXData";

		private static string m_strFieldName = "SmokeRoomId";

		private static XDataManager m_xdataMgr = null;
	}
}
